package top.linyuxb.lycloud.admin.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.linyuxb.lycloud.admin.entity.LyCloudUserEntity;
import top.linyuxb.lycloud.admin.service.ILyConfPermissionService;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/8/7 11:10
 * @Desc:
 */
@Slf4j
@Service(value = "lyConfPermissionService")
public class LyConfPermissionServiceImpl implements ILyConfPermissionService {
    @Override
    public Boolean ifHasProjectPermission(LyCloudUserEntity loginUser, String loginEnv, String appname) {
        if (loginUser.getPermission() == 1) {
            return Boolean.TRUE;
        }
        if (ArrayUtils.contains(StringUtils.split(loginUser.getPermissionData(), ","),
                (appname.concat("#").concat(loginEnv)))) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean getPermissionServers(LyCloudUserEntity loginUser, Set<String> servers) {
        if (loginUser.getPermission() == 1) {
            return Boolean.TRUE;
        }
        if (StringUtils.isNotBlank(loginUser.getPermissionData())) {
            servers.addAll(Stream.of(loginUser.getPermissionData().split(",")).collect(Collectors.toSet()));
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean getPermissionApps(LyCloudUserEntity loginUser, Set<String> apps) {
        if (loginUser.getPermission() == 1) {
            return Boolean.TRUE;
        }
        if (StringUtils.isNotBlank(loginUser.getPermissionData())) {
            String[] split = loginUser.getPermissionData().split(",");
            for (String data : split) {
                String[] split1 = data.split("#");
                apps.add(split1[0]);
            }
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean getPermissionEnvs(LyCloudUserEntity loginUser, Set<String> envs) {
        if (loginUser.getPermission() == 1) {
            return Boolean.TRUE;
        }
        if (StringUtils.isNotBlank(loginUser.getPermissionData())) {
            String[] split = loginUser.getPermissionData().split(",");
            for (String data : split) {
                String[] split1 = data.split("#");
                envs.add(split1[1]);
            }
        }
        return Boolean.FALSE;
    }
}
